<template>
	<div class="front" v-loading="loading" element-loading-text="拼命加载中..." element-loading-spinner="el-icon-loading" element-loading-background="#fff">
		<el-input v-model="searchText" style="width:100%;margin: 10px 0;" placeholder="输入关键字"></el-input>
		<div class="tree bj bg-white">
			<el-scrollbar style="height: 100%;">
				<el-tree :data="treeData" :props="defaultProps" node-key="id" :filter-node-method="filterNode" :default-expanded-keys="[systemId]" ref="tree" :indent="10" @node-click="nodeClick" :default-expand-all="false" :highlight-current="true"></el-tree>
			</el-scrollbar>
		</div>
	</div>
</template>
<script>
export default {
	data() {
		return {
			loading: true,
			searchText: '',
			treeData: [],
			defaultProps: {
				label: 'name',
                children: 'subDepartment'
			}
		}
	},
	watch:{
        searchText(val){             
            this.$refs.tree.filter(val);
        }
    },
	computed: {
		systemId() {
			return this.$store.state.systemId;
		},
		companyName() {
			return this.$store.state.companyName;
		}
	},
	methods: {
		getTreeData() {
			this.loading = true;
			this.$http.get('department/selectObject?systemId=' + this.systemId).then(res => {
				if(res.data.code == 20001) {
					let data = {
			            name: this.companyName,
			            id: this.systemId,
			            level: 0,
			            subDepartment: []
			        }
			        setTimeout(() => {
			        	if(res.data.data) {
							data['subDepartment'] = res.data.data;		//将部门数据放到公司节点上
							this.treeData.splice(0, 1, data);
						}
						this.loading = false;
			        }, 500);
				} else {
					setTimeout(() => {
			        	data['subDepartment'] = [];		//将部门数据放到公司节点上
						this.treeData.splice(0, 1, data);
						this.loading = false;
			        }, 500);
				}
			}).catch(() => {
				setTimeout(() => {
		        	data['subDepartment'] = [];		//将部门数据放到公司节点上
					this.treeData.splice(0, 1, data);
					this.loading = false;
		        }, 500);
			})
		},
		filterNode(value, data) {           //部门选择里面的搜索框
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
		nodeClick(row) {
			if(row.subDepartment.length == 0){
                this.$store.commit('empStore/updateLastDepartmentName', row['name']);
                this.$store.commit('empStore/updateParentId', row['id']);
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            }else{
                this.$message.error('选择末级部门名称');
            }
		}
	},
	created() {
		this.getTreeData();
	}
}
</script>
<style scoped>
	.tree {height: calc(100% - 60px);box-sizing: border-box;padding: 5px 0;}
	.tree .el-tree {height: 100% !important;overflow-y: auto !important;}
</style>